<template>
  <div class="update-avatar">
    <img class="img" :src="img" ref="img" />
    <div class="toolbar">
      <span class="cancel" @click="$emit('close')">取消</span>
      <span class="confirm" @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";

import { updateUserAvatar } from "@/api/user.js";
export default {
  props: {
    img: {
      type: [String, Object],
      required: true,
    },
  },
  data() {
    return {
      cropper: null,
    };
  },
  // 裁剪区域处理
  mounted() {
    const image = this.$refs.img;
    this.cropper = new Cropper(image, {
      // crop(event) {
      //   console.log(event.detail.x);
      //   console.log(event.detail.y);
      // },
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: "move", // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false, // 关闭默认背景
    });
  },
  methods: {
    // 确认之后的处理函数
    onConfirm() {
      // 基于服务端的裁切使用getDate方法获取裁切参数
      // console.log(this.cropper.getData());
      // 纯客户端的使用getCroppedCanvas
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this.updateAvatar(blob);
      });
    },
    // 接收到头像数据并渲染
    async updateAvatar(blob) {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      try {
        const formData = new FormData();
        formData.append("photo", blob);
        const { data } = await updateUserAvatar(formData);
        // 关闭弹层，更新视图
        this.$emit("close");
        this.$emit("update-avatar", data.data.photo);
        this.$toast("更新成功");
      } catch (err) {
        this.$toast("更新失败");
      }
    },
  },
};
</script>

<style scoped lang='less'>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .img {
    display: block;
    max-width: 100%;
  }
  .toolbar {
    position: fixed;
    bottom: 0px;
    left: 0px;
    right: 0px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
